package com.awesome.common.base.mvp

import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.os.Bundle
import com.awesome.common.util.ActivityManager
import com.awesome.common.util.log.ShowLogUtil

/**
 * Author: JFangZ
 * Email:  janezhang1901@163.com
 * Date:2021/4/27 18:30
 * Description:生命周期感知
 */
class ActLifecycle : ActivityLifecycleCallbacks {


    private var countActivity = 0
    //app状态 ture前台 false后台
    private var isState = false


    override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {

        ActivityManager.addActivity(activity)
    }

    override fun onActivityStarted(activity: Activity) {
        countActivity++
        if (countActivity == 1 && !isState) {
            ShowLogUtil.debug("onActivityStarted: 应用进入前台")
            isState = true
            handleAppState() //app从后台进入前台了，在这个自定义的方法里处理具体的业务
        }


    }


    override fun onActivityResumed(activity: Activity) {}
    override fun onActivityPaused(activity: Activity) {}
    override fun onActivityStopped(activity: Activity) {
        countActivity--
        if (countActivity <= 0 && isState) {
            ShowLogUtil.debug("onActivityStarted: 应用进入后台")
            isState = false
            handleAppState() //app从前台进入后台了，在这个自定义的方法里处理具体的业务
        }

    }

    override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {}

    override fun onActivityDestroyed(activity: Activity) {
        ActivityManager.removeActivity(activity)
    }

    /**
     * app从后台进入前台了，在这个自定义的方法里处理具体的业务
     */
    private fun handleAppState() {
        if (::stateListener.isInitialized) {
            stateListener(isState)
        }
    }
    /**
     * 事件回调 true app从后台进入前台了 , false app从前台进入后台
     */

    fun setOnStateListener(listener: (isState:Boolean) -> Unit) {
        this.stateListener = listener
    }

    private lateinit var stateListener: (isState:Boolean) -> Unit
}